package com.moli.iov.base.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;;
import com.moli.iov.base.cache.redis.VehicleFenceBindingCacheService;
import com.moli.iov.base.enums.YesOrNoEnum;
import com.moli.iov.base.model.VehicleFenceBindingParam;
import com.moli.iov.base.model.dto.req.VehicleFenceBindingDto;
import com.moli.iov.base.model.po.VehicleFence;
import com.moli.iov.base.model.po.VehicleFenceBinding;
import com.moli.iov.base.service.IVehicleFenceBindingService;
import com.moli.iov.base.service.IVehicleFenceService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.exception.BusinessException;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.base.mapper.VehicleFenceBindingMapper;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 围栏绑定表  服务实现类
 * </p>
 *
 * @author wanghualin
 * @since 2019-09-03
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class VehicleFenceBindingServiceImpl extends
    ServiceImpl<VehicleFenceBindingMapper, VehicleFenceBinding> implements
    IVehicleFenceBindingService {

  @Autowired
  private VehicleFenceBindingCacheService vehicleFenceBindingCacheService;
  @Autowired
  private IVehicleFenceService iVehicleFenceService;

  @Override
  public RestResponse saveVehicleFenceBinding(VehicleFenceBindingDto vehicleFenceBindingDto,
      VehicleFence vehicleFence) {
    ValidationUtils.validateBean(vehicleFenceBindingDto);
    VehicleFenceBinding fenceBinding = new VehicleFenceBinding();
    CommonUtils.copyProperties(vehicleFenceBindingDto, fenceBinding);
    boolean save = this.save(fenceBinding);
    if (save) {
      vehicleFenceBindingCacheService.setVehicleFenceBinding(fenceBinding, vehicleFence);
    }
    return save ? RestResponse.success() : RestResponse.failure("添加失败");
  }


  @Override
  public RestResponse deleteVehicleFenceBinding(VehicleFenceBindingDto vehicleFenceBindingDto,
      VehicleFence vehicleFence) {
    ValidationUtils.validateBean(vehicleFenceBindingDto);
    VehicleFenceBinding fenceBinding = new VehicleFenceBinding();
    CommonUtils.copyProperties(vehicleFenceBindingDto, fenceBinding);
    boolean save = this.saveOrUpdate(fenceBinding);
    if (save) {
      vehicleFenceBindingCacheService.deleteVehicleFenceBinding(fenceBinding, vehicleFence);
    }
    return save ? RestResponse.success() : RestResponse.failure("删除失败");
  }

  @Override
  public RestResponse saveBatchVehicleFenceBinding(List<VehicleFenceBinding> list,
      VehicleFence vehicleFence) {
    if (CollectionUtils.isEmpty(list) || vehicleFence == null) {
      throw new BusinessException("参数为空");
    }
    boolean batch = this.saveBatch(list);
    if (batch) {
      vehicleFenceBindingCacheService.saveBatch(list, vehicleFence);
    }
    return batch ? RestResponse.success() : RestResponse.failure("删除失败");
  }

  @Override
  public List<VehicleFenceBinding> listVehicleFenceBinding(Long fenceId, List<String> listVin) {
    VehicleFenceBindingParam bindingParam = new VehicleFenceBindingParam();
    bindingParam.queryEqFenceId(fenceId);
    bindingParam.queryInVin(listVin);
    return list(bindingParam.get());
  }

  @Override
  public RestResponse deleteBatchVehicleFenceBinding(List<VehicleFenceBinding> list,
      VehicleFence vehicleFence) {
    if (CollectionUtils.isEmpty(list) || vehicleFence == null) {
      throw new BusinessException("参数为空");
    }
    list.forEach(vehicleFenceBinding ->vehicleFenceBinding.setIsDelete(YesOrNoEnum.YES.getCode()) );
    boolean batch = saveOrUpdateBatch(list);
    if (batch) {
      vehicleFenceBindingCacheService.deleteBatch(list, vehicleFence);
    }
    return batch ? RestResponse.success() : RestResponse.failure("删除失败");
  }

  @Override
  public int countVehicleFenceBinding(Long id) {
    ValidationUtils.validateBean(id);
    Set<String> set = vehicleFenceBindingCacheService.listVehicleFenceById(id);
    if (CollectionUtils.isEmpty(set)) {
      VehicleFenceBindingParam bindingParam = new VehicleFenceBindingParam();
      bindingParam.queryEqFenceId(id);
      return count(bindingParam.get());
    } else {
      return set.size();
    }
  }

  @Override
  public List<VehicleFence> listFenceIdByVin(String vin) {
    ValidationUtils.validateBean(vin);
    Set<String> jsonStr = vehicleFenceBindingCacheService.listFenceIdByVin(vin);
    if (CollectionUtils.isEmpty(jsonStr)) {
      VehicleFenceBindingParam bindingParam = new VehicleFenceBindingParam();
      bindingParam.queryEqVin(vin);
      List<VehicleFenceBinding> list = list(bindingParam.get());
      if (!CollectionUtils.isEmpty(list)) {
        List<VehicleFence> vehicleFences = new ArrayList<>();
        for (VehicleFenceBinding binding : list) {
          VehicleFence vehicleFence = iVehicleFenceService.getVehicleFence(binding.getFenceId());
          if (vehicleFence != null) {
            vehicleFences.add(vehicleFence);
            vehicleFenceBindingCacheService.setVehicleFenceBinding(binding, vehicleFence);
          }
        }
        return vehicleFences;
      }
    } else {
      List<VehicleFence> collect = jsonStr.stream().map(s -> JsonUtils.parse(s, VehicleFence.class))
          .collect(Collectors.toList());
      return collect;
    }
    return new ArrayList<>();
  }

  @Override
  public void initVehicleFenceBinding() {
    //清空缓存
    vehicleFenceBindingCacheService.cleanVehicleFenceBindingCache();
    VehicleFenceBindingParam param = new VehicleFenceBindingParam();
    List<VehicleFenceBinding> list = list(param.get());
    List<VehicleFence> vehicleFences = iVehicleFenceService.listVehicleFences();
        // List<VehicleFence> vehicleFences = iVehicleFenceService.listVehicleFences();
    if (!CollectionUtils.isEmpty(vehicleFences)&&!CollectionUtils.isEmpty(list)){
      vehicleFenceBindingCacheService.saveBatchs(list,vehicleFences);
            //更新围栏绑定数据
            Map<Long, List<VehicleFenceBinding>> collect = list.stream().collect(Collectors.groupingBy(VehicleFenceBinding::getFenceId));
            List<VehicleFence> update = new ArrayList<>();
            for (VehicleFence vehicleFence : vehicleFences) {
                if (collect.get(vehicleFence.getId()) != null) {
                    vehicleFence.setTotal(collect.get(vehicleFence.getId()).size());
                    update.add(vehicleFence);
                }else{
                  vehicleFence.setTotal(0);
                  update.add(vehicleFence);
                }
    }
            if (!CollectionUtils.isEmpty(update)){
                boolean b = iVehicleFenceService.saveOrUpdateBatch(update);
                log.info("更新围栏绑定车辆：",b);
            }
        }

  }

  @Override
  public List<VehicleFenceBinding> listVehicleFenceBinding(List<String> vinList) {
    VehicleFenceBindingParam bindingParam = new VehicleFenceBindingParam();
    bindingParam.queryInVin(vinList);
    return list(bindingParam.get());
  }

    @Override
    public List<VehicleFenceBinding> listVehicleFenceBinding(String vin, Integer alarmType) {
        VehicleFenceBindingParam bindingParam = new VehicleFenceBindingParam();
        bindingParam.queryEqVin(vin);
        bindingParam.queryEqAlarmType(alarmType);
        return list(bindingParam.get());
    }


}
